package com.bingkaimedia.merchantbeta.app;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.bingkaimedia.merchantbeta.R;
import com.bingkaimedia.merchantbeta.libs.JSONfunctions;
import com.bingkaimedia.merchantbeta.libs.LazyAdapter_Semua;
import com.bingkaimedia.merchantbeta.libs.SessionManager;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

@SuppressLint("NewApi")
public class List_Data_Semua extends Fragment {

int current_page = 0;
	

	// XML node keys
	//static final String KEY_SONG = "song"; // parent node
	public static final String KEY_VOUCHER_ID = "voucher_id";
	public static final String KEY_VOUCHER_NAME = "voucher_name"; 
	public static final String KEY_VOUCHER_TOTAL = "voucher_total";
	//public static final String KEY_VOUCHER_TERSEDIA = "voucher_tersedia";
	public static final String KEY_MERCHANT_NAME = "merchant_name";
	public static final String KEY_MERCHANT_CATEGORY = "voucher_category";
	public static final String KEY_MERCHANT_PHOTO = "merchant_photo";
	public static final String KEY_VOUCHER_DETAIL = "voucher_detail";
	public static final String KEY_VOUCHER_DESCRIPTION = "voucher_description";
	public static final String KEY_MERCHANT_ID = "merchant_id";
	
	public static final String KEY_MY_CHANNEL_ID = "my_channel_id";
	public static final String KEY_CHANNEL_ID = "channel_id";
	public static final String KEY_USERS_ID = "users_id";
	public static final String KEY_CHANNEL_NAME = "channel_name";
	public static final String KEY_CHANNEL_ADDRESS = "channel_address";
	public static final String KEY_CHANNEL_PHOTO = "channel_photo";
	public static final String KEY_CHANNEL_NOTE = "channel_note";
	
	private String xml_voucher_id;
	private String xml_voucher_name;
	private String xml_voucher_total;
	//private String xml_voucher_tersedia;
	private String xml_voucher_description;
	private String xml_voucher_detail;
	private String xml_voucher_date;
	private String xml_merchant_id;
	private String xml_merchant_name;
	private String xml_merchant_category;
	private String xml_merchant_photo;
	private String xml_transaction_id;
	private String xml_transaction_date;
	private String xml_transaction_image;
	private String xml_transaction_status;
	

	private String xml_my_channel_id;
	private String xml_channel_id;
	private String xml_users_id;
	private String xml_channel_name;
	private String xml_channel_photo;
	private String xml_channel_note;
	private String xml_channel_address;
	
	private static String session_userid;
	private static String session_username;
	private static String session_password;
	private static String session_email;
	private static String session_country;
	private static String session_country_name;
	private static String session_city;
	private static String session_city_name;
	private static String session_checked;
	private static String session_channel;
	private static String session_category;
	private static String session_category_name;
    
	
	static final int MENU_MANUAL_REFRESH = 0;
	static final int MENU_DISABLE_SCROLL = 1;
	static final int MENU_SET_MODE = 2;
	static final int MENU_DEMO = 3;
	
	private PullToRefreshListView mPullRefreshListView;
	ListView actualListView;
	
	private String id_;

	private int count;
	private String json;
	private String result;
	private JSONObject jsonobject;
	public String code;
	public String msg;
	 
	
	public View viewfragment;
	 
	SessionManager session;
	
	private LazyAdapter_Semua adapter;
	ArrayList<HashMap<String, String>> menuItems;
	ProgressDialog pDialog;
	HashMap<String, String> map = new HashMap<String, String>();
	
	ArrayList<HashMap<String, String>> diskonba_list_semua = new ArrayList<HashMap<String, String>>();
	
 
	    
	
	public void onBackPressed() {
		// TODO Auto-generated method stub
		//super.onBackPressed();
	}
	
	public static List_Data_Semua newInstance(int page, String title) {
		List_Data_Semua fragmentFirst = new List_Data_Semua();
        Bundle args = new Bundle();
        args.putInt("someInt", page);
        args.putString("someTitle", title);
        fragmentFirst.setArguments(args);
        return fragmentFirst;
    }


	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
    }
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		viewfragment = inflater.inflate(R.layout.list_data_semua, container, false);

		deklarasi_refresh();
		
		deklarasi_list();
				
		new loadListView().execute();
	 
		aksi_klik();			 

		return viewfragment;
		 
		
	}
	
 
	public void deklarasi_refresh(){
		//loading
		mPullRefreshListView = (PullToRefreshListView) viewfragment.findViewById(R.id.pull_refresh_list);

		mPullRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				String label = DateUtils.formatDateTime(getActivity().getApplicationContext(), System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
 
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label); 
				new loadMoreListView().execute();
			}
		}); 
  
		mPullRefreshListView.setOnLastItemVisibleListener(new OnLastItemVisibleListener() { 
			@Override
			public void onLastItemVisible() {
				//Toast.makeText(FragmentSenin.this.getActivity(), "End of List!", Toast.LENGTH_SHORT).show();
			}
		});
			
		actualListView = mPullRefreshListView.getRefreshableView();
 
		registerForContextMenu(actualListView);
		
		
		//sound
		/*
		SoundPullEventListener<ListView> soundListener = new SoundPullEventListener<ListView>(FragmentSenin.this.getActivity());
		soundListener.addSoundEvent(State.PULL_TO_REFRESH, R.raw.pull_event);
		soundListener.addSoundEvent(State.RESET, R.raw.reset_sound);
		soundListener.addSoundEvent(State.REFRESHING, R.raw.refreshing_sound);
		mPullRefreshListView.setOnPullEventListener(soundListener);
		*/
		
		//variasi
		mPullRefreshListView.setMode(mPullRefreshListView.getMode() == Mode.BOTH ? Mode.PULL_FROM_START: Mode.BOTH);
		//mPullRefreshListView.setRefreshing(false);
		//mPullRefreshListView.setScrollingWhileRefreshingEnabled(!mPullRefreshListView.isScrollingWhileRefreshingEnabled());
		//mPullRefreshListView.demo();		
	}
	
	
	
	
	public void deklarasi_list(){ 
		
		session = new SessionManager(getActivity().getApplicationContext());
	    
	    HashMap<String, String> user = session.getUserDetails();
	     
	    // name
	    session_userid = user.get(SessionManager.id_users);
	    session_username = user.get(SessionManager.username);
	    session_password = user.get(SessionManager.password);
	    session_email = user.get(SessionManager.email);
	    session_country = user.get(SessionManager.country);
	    session_country_name = user.get(SessionManager.country_name);
	    session_city = user.get(SessionManager.city);
	    session_city_name = user.get(SessionManager.city_name);
	    session_checked = user.get(SessionManager.checked);
	    session_channel = user.get(SessionManager.channel);
	    session_category = user.get(SessionManager.category);
	    session_category_name = user.get(SessionManager.category_name);
	    
	    ////System.out.println("session");
	    ////System.out.println(session_userid);
	    ////System.out.println(session_username);
	    ////System.out.println(session_password);
	    ////System.out.println(session_email);
	    ////System.out.println(session_country);
	    ////System.out.println(session_country_name);
	    ////System.out.println(session_city);
	    ////System.out.println(session_city_name);
	    ////System.out.println(session_checked);
	    ////System.out.println(session_channel);
	    ////System.out.println(session_category);
	    ////System.out.println(session_category_name);
	     
	    
	    TextView city_category = (TextView)viewfragment.findViewById(R.id.city_category);
	    if (session_category == "")
	    {
	    	city_category.setText(session_city_name + " - " + "[ ALL ]");
	    }
	    else
	    {
	    	city_category.setText(session_city_name + " - " + "[ " + session_category_name +" ]");
	    }
	}
	
	
	
	public void aksi_klik(){
		
		actualListView.setOnItemClickListener(new OnItemClickListener() { 
			@Override
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
							// getting values from selected ListItem
				String list_id = ((TextView) view.findViewById(R.id.txt_voucher_id))
						.getText().toString();
	
				////System.out.println("masuk klik");
				////System.out.println(list_id);
				// Starting new intent
				Intent in = new Intent(getActivity(),
						List_Data_Detail.class);
				in.putExtra(KEY_VOUCHER_ID, list_id);
				startActivity(in);
			}
		});  
	}
	
	
	
	
	@SuppressLint("NewApi")
	private class loadListView extends AsyncTask<Void, Void, Void>  {

		@Override
		protected void onPreExecute() {

		}

		protected Void doInBackground(Void... unused) {
		 
			String result = null;
			InputStream is = null;
			StringBuilder sb=null; 

			ArrayList nameValuePairs = new ArrayList();
			
			
	    	Global.URL = Global.link_list_data_semua + session_city + "&page=" + current_page+ "&category=" + session_category+ "&users=" + session_userid;
			////System.out.println(Global.URL); 
	      
			// Next page request

			Global.URL = Global.URL.replace(" ", "%20");
			
			code="99";
			msg="Not connected to server";
			////System.out.println("Mulai do in background");
 
			try{ 
				json=JSONfunctions.getStringContent(Global.URL);
				jsonobject=new JSONObject(json); 
				code=jsonobject.getString("code");
				msg=jsonobject.getString("msg");
				 
			}
			catch (Exception e) 
			{
				e.printStackTrace();
				//System.out.println("catch code msg");
				//System.out.println(e);
				//pDialog.dismiss();
				//Toast.makeText(getApplicationContext(), "Something wrong in your connection", Toast.LENGTH_LONG).show();
			
			}
			
			//System.out.println("code "+code);
			if(code.equalsIgnoreCase("99")){
				try{ 
					//System.out.println(Global.URL);
					//json=JSONfunctions.getStringContent2(Global.URL);
					//System.out.println(json); 
					 
				}
				catch (Exception e) 
				{
					e.printStackTrace();
					//System.out.println("catch 1");
					//System.out.println(e);

					//pDialog.dismiss();
					//Toast.makeText(getApplicationContext(), "Something wrong in your connection (1)", Toast.LENGTH_LONG).show();
				
				}
			}
		  
			return null;
		}
		
		
		protected void onPostExecute(Void unused) {
			  
			count = 0;  
			result = json; 
			diskonba_list_semua.clear(); 
			
			
			

			if(code.equalsIgnoreCase("0")){
				
				Toast.makeText(getActivity().getBaseContext(), msg, Toast.LENGTH_LONG).show();
			}
			else{
				try{
			      	JSONArray jArray = new JSONArray(result);
			      	JSONObject json_data=null;

			      	////System.out.println("array length");
			      	////System.out.println(jArray.length());
			      	
			      	for(int i=0;i<jArray.length();i++){
						json_data = jArray.getJSONObject(i); 
						
						xml_voucher_id = json_data.getString(KEY_VOUCHER_ID);
						xml_voucher_name = json_data.getString(KEY_VOUCHER_NAME);
						//xml_voucher_total = json_data.getString(KEY_VOUCHER_TOTAL);
						//xml_voucher_tersedia = json_data.getString(KEY_VOUCHER_TERSEDIA);
						xml_voucher_detail = json_data.getString(KEY_VOUCHER_DETAIL);
						xml_merchant_id = json_data.getString(KEY_MERCHANT_ID);
						xml_merchant_category = json_data.getString(KEY_MERCHANT_CATEGORY);
						xml_merchant_name = json_data.getString(KEY_MERCHANT_NAME);
						xml_merchant_photo = json_data.getString(KEY_MERCHANT_PHOTO);
						xml_channel_name = "Channel : " + json_data.getString(KEY_CHANNEL_NAME);
						 
						////System.out.println(xml_voucher_id);
						////System.out.println(xml_voucher_name);
						//////System.out.println("Total - " + xml_voucher_total);
						//////System.out.println("Tersedia - " + xml_voucher_tersedia);
						////System.out.println(xml_voucher_detail); 
						////System.out.println(xml_merchant_id);
						////System.out.println(xml_merchant_category);
						////System.out.println(xml_merchant_name);
						////System.out.println(xml_channel_name);
						////System.out.println(Global.path + xml_merchant_photo);
						 
						
						HashMap<String, String> map = new HashMap<String, String>();
						//Element e = (Element) nl.item(i);
						// adding each child node to HashMap key => value
						map.put(KEY_VOUCHER_ID, xml_voucher_id);
						map.put(KEY_VOUCHER_DETAIL, xml_voucher_detail);
						map.put(KEY_MERCHANT_NAME, xml_merchant_name);
						map.put(KEY_CHANNEL_NAME, xml_channel_name);
						map.put(KEY_VOUCHER_NAME, xml_voucher_name); 
						map.put(KEY_MERCHANT_CATEGORY, xml_merchant_category); 
						//map.put(KEY_VOUCHER_TERSEDIA,  xml_voucher_tersedia + " Point"); 
						map.put(KEY_MERCHANT_PHOTO, Global.path + xml_merchant_photo);

						// adding HashList to ArrayList
							diskonba_list_semua.add(map);
							
				      	}
			      	
		 		}catch(JSONException e1){ 
					//System.out.println("semua catch 2");
					//System.out.println(e1);
					Toast.makeText(getActivity().getBaseContext(), "Something wrong in your connection (2)", Toast.LENGTH_LONG).show();
				}catch (ParseException e1){ 
					//System.out.println("semua catch 3");
					//System.out.println(e1);
					Toast.makeText(getActivity().getBaseContext(), "Something wrong in your connection (3)", Toast.LENGTH_LONG).show();	
				} 
			}
			
	 		
		  
			 
			
			 
			adapter = new LazyAdapter_Semua(getActivity(), diskonba_list_semua); 

			actualListView.setAdapter(null);
			actualListView.setAdapter(adapter);
		}
	}
 
	@SuppressLint("NewApi")
	private class loadMoreListView extends AsyncTask<Void, Void, Void>  {

		@Override
		protected void onPreExecute() {

		}

		protected Void doInBackground(Void... unused) {
			
			current_page += 1;
			String result = null;
			InputStream is = null;
			StringBuilder sb=null; 

			ArrayList nameValuePairs = new ArrayList();
			
			Global.URL = Global.link_list_data_semua + session_city + "&page=" + current_page+ "&category=" + session_category+ "&users=" + session_userid;
			////System.out.println(Global.URL); 
	      
			
			code="99";
			msg="Not connected to server";
			////System.out.println("Mulai do in background");
 
			try{ 
				json=JSONfunctions.getStringContent(Global.URL);
				jsonobject=new JSONObject(json); 
				code=jsonobject.getString("code");
				msg=jsonobject.getString("msg");
				 
			}
			catch (Exception e) 
			{
				e.printStackTrace();
				//System.out.println("catch code msg");
				//System.out.println(e);
				pDialog.dismiss();
				//Toast.makeText(getApplicationContext(), "Something wrong in your connection", Toast.LENGTH_LONG).show();
			
			}
			
			//System.out.println("code "+code);
			if(code.equalsIgnoreCase("99")){
				try{ 
					//System.out.println(Global.URL);
					//json=JSONfunctions.getStringContent2(Global.URL);
					//System.out.println(json); 
					 
				}
				catch (Exception e) 
				{
					e.printStackTrace();
					//System.out.println("catch 1");
					//System.out.println(e);

					pDialog.dismiss();
					//Toast.makeText(getApplicationContext(), "Something wrong in your connection (1)", Toast.LENGTH_LONG).show();
				
				}
			}
		  
			return null;
		}
		
		
		protected void onPostExecute(Void unused) {
			 
			////System.out.println("onpostexecute"); 
			count = 0; 

			result = json;

			if(code.equalsIgnoreCase("0")){
				
				Toast.makeText(getActivity().getBaseContext(), msg, Toast.LENGTH_LONG).show();
			}
			else{
				try{
			      	JSONArray jArray = new JSONArray(result);
			      	JSONObject json_data=null;
	
			      	////System.out.println("array length");
			      	////System.out.println(jArray.length());
			      	
			      	for(int i=0;i<jArray.length();i++){
						json_data = jArray.getJSONObject(i); 
						
						xml_voucher_id = json_data.getString(KEY_VOUCHER_ID);
						xml_voucher_name = json_data.getString(KEY_VOUCHER_NAME);
						//xml_voucher_total = json_data.getString(KEY_VOUCHER_TOTAL);
						//xml_voucher_tersedia = json_data.getString(KEY_VOUCHER_TERSEDIA);
						xml_voucher_detail = json_data.getString(KEY_VOUCHER_DETAIL);
						xml_merchant_id = json_data.getString(KEY_MERCHANT_ID);
						xml_merchant_category = json_data.getString(KEY_MERCHANT_CATEGORY);
						xml_merchant_name = json_data.getString(KEY_MERCHANT_NAME);
						xml_merchant_photo = json_data.getString(KEY_MERCHANT_PHOTO);
						xml_channel_name = "Channel : " + json_data.getString(KEY_CHANNEL_NAME);
						 
						////System.out.println(xml_voucher_id);
						////System.out.println(xml_voucher_name);
						//////System.out.println("Total - " + xml_voucher_total);
						//////System.out.println("Tersedia - " + xml_voucher_tersedia);
						////System.out.println(xml_voucher_detail); 
						////System.out.println(xml_merchant_id);
						////System.out.println(xml_merchant_category);
						////System.out.println(xml_merchant_name);
						////System.out.println(xml_channel_name);
						////System.out.println(Global.path + xml_merchant_photo);
						 
						
						HashMap<String, String> map = new HashMap<String, String>();
						//Element e = (Element) nl.item(i);
						// adding each child node to HashMap key => value
						map.put(KEY_VOUCHER_ID, xml_voucher_id);
						map.put(KEY_VOUCHER_DETAIL, xml_voucher_detail);
						map.put(KEY_MERCHANT_NAME, xml_merchant_name);
						map.put(KEY_CHANNEL_NAME, xml_channel_name);
						map.put(KEY_VOUCHER_NAME, xml_voucher_name); 
						map.put(KEY_MERCHANT_CATEGORY, xml_merchant_category); 
						//map.put(KEY_VOUCHER_TERSEDIA,  xml_voucher_tersedia + " Point"); 
						map.put(KEY_MERCHANT_PHOTO, Global.path + xml_merchant_photo);
	
						// adding HashList to ArrayList
							diskonba_list_semua.add(map);
						}
			      	
				}catch(JSONException e1){ 
					//System.out.println("catch 2");
					//System.out.println(e1);
					Toast.makeText(getActivity().getBaseContext(), "Something wrong in your connection (2)", Toast.LENGTH_LONG).show();
				}catch (ParseException e1){ 
					//System.out.println("catch 3");
					//System.out.println(e1);
					Toast.makeText(getActivity().getBaseContext(), "Something wrong in your connection (3)", Toast.LENGTH_LONG).show();	
				} 
			}
				 				
			 
		 
			
			int currentPosition = actualListView.getFirstVisiblePosition();
			
			////System.out.println("getFirstVisiblePosition " + actualListView.getFirstVisiblePosition());
			////System.out.println("getFooterViewsCount " + actualListView.getFooterViewsCount());
			////System.out.println("getHeaderViewsCount " + actualListView.getHeaderViewsCount());
			////System.out.println("getLastVisiblePosition " + actualListView.getLastVisiblePosition());
			
			adapter = new LazyAdapter_Semua(getActivity(), diskonba_list_semua); 
			actualListView.setAdapter(adapter);
      	
			// Setting new scroll position
			////System.out.println("current" + currentPosition + 1);
			actualListView.setSelectionFromTop(currentPosition + 1, 0); 
			mPullRefreshListView.onRefreshComplete();	 
			
		}
	} 
	 
 
	
}
